package cn.tonyqiu.gaecash.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.MessageSource;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

import cn.tonyqiu.gaecash.model.Label;
import cn.tonyqiu.gaecash.model.LabelExistingException;

import com.google.appengine.api.users.UserServiceFactory;

public class LabelController extends MultiActionController {

	private MessageSource messages = null;
	
	public ModelAndView action(HttpServletRequest req, HttpServletResponse resp)
			throws Exception {
		return getAll(req, resp);
	}

	public void add(HttpServletRequest req, HttpServletResponse resp)
			throws Exception {
		Label label = new Label();
		String name = req.getParameter("name");
		label.setName(name);
		label.setUser(UserServiceFactory.getUserService().getCurrentUser());
		try{
		label = label.add();
		}catch(LabelExistingException e){
			//e.printStackTrace();
			resp.getWriter().write("-1:"+messages.getMessage("labelExsting",new Object[]{name},name+"已经存在，请采用其他名称新建标签",null));
			return;
		}
		resp.getWriter().write(label.getKeyString());
	}

	public ModelAndView getAll(HttpServletRequest req, HttpServletResponse resp)
			throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		List<Label> labels = Label.getAll(UserServiceFactory.getUserService()
				.getCurrentUser());
		map.put("labels", labels);
		return new ModelAndView("WEB-INF/pages/label.jsp", map);
	}

	public void edit(HttpServletRequest req, HttpServletResponse resp)
			throws Exception {
		String name = req.getParameter("name");
		String keyString = req.getParameter("keyString");
		Label label = new Label();
		try {
		label.setName(name);
		label.setKeyString(keyString);
		label.update();
		}catch(LabelExistingException e){
			//e.printStackTrace();
			resp.getWriter().write(messages.getMessage("labelExsting",new Object[]{name},name+"已经存在，请采用其他名称修改标签",null));
			return;
		}
		return;
	}

	public ModelAndView del(HttpServletRequest req, HttpServletResponse resp)
			throws Exception {
		String delIdString = req.getParameter("delIdString");
		for(String keyString:delIdString.split(",")){
			Label.del(keyString);
		}
		return null;
	}

	public MessageSource getMessages() {
		return messages;
	}

	public void setMessages(MessageSource messages) {
		this.messages = messages;
	}

}
